package com.sjtu.bookread;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.*;
import android.widget.*;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.drawerlayout.widget.DrawerLayout;

import com.sjtu.bookread.obj.ChapterObj1;
import com.sjtu.bookread.service.RecomService;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class ReadPageActivity1 extends AppCompatActivity {
    private float current_speed = 0;
    private ScrollView scrollView;
    private TextView textView;
    private TextView titleView;
    private TextView bookTitleView;
    private int total_chapter = 10;
    private VelocityTracker velocityTracker = null;
    public long last_record_time = 0;
    private List<Float> sequence = new ArrayList<>();

    private String book_text;
    private String chapter_title;
    private int book_id;
    private String book_name;
    private int currChapter = 0;

    private Timer timer;
    private TimerTask timerTask;

    private Handler handler;



    @SuppressLint({"ClickableViewAccessibility", "HandlerLeak"})
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        changeStatusIconCollor(true);
        Window window =this.getWindow();
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(ContextCompat.getColor(this,R.color.PapayaWhip));

        setContentView(R.layout.activity_read_page1);


        //从传递的参数获取书籍
        Intent intent = this.getIntent();
        Bundle bundle = intent.getExtras();
        book_id = bundle.getInt("bookid");
        book_name = bundle.getString("bookname");

        (findViewById(R.id.read_page_next_button)).setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (currChapter < total_chapter - 1) {
                            currChapter += 1;
                        }
                        init_chapter();
                        (findViewById(R.id.read_page1_scroll)).setScrollY(0);
                    }
                }
        );

        (findViewById(R.id.footer_item_out)).setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ReadPageActivity1.this.finish();
                    }
                }
        );

        scrollView = findViewById(R.id.read_page1_scroll);
        textView = findViewById(R.id.read_page1_content);
        titleView = findViewById(R.id.read_page_title);
        bookTitleView = findViewById(R.id.reader_book_title);
        bookTitleView.setText(book_name);

        final ListView listView = findViewById(R.id.nav_list_view);


        handler = new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                textView.setText(book_text);
                titleView.setText(chapter_title);

                if (currChapter>=total_chapter-1) {
                    ((Button)findViewById(R.id.read_page_next_button)).setVisibility(View.GONE);
                }
                else {
                    ((Button)findViewById(R.id.read_page_next_button)).setVisibility(View.VISIBLE);
                }

                ((DrawerLayout)findViewById(R.id.drawer_layout)).closeDrawer(Gravity.LEFT);

                ArrayList<String> arrayList = new ArrayList<String>();
                for (int i=1; i<=total_chapter; i++) {
                    arrayList.add("第"+i+"章");
                }
                ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
                        ReadPageActivity1.this,  android.R.layout.simple_list_item_1, arrayList);
                listView.setAdapter(arrayAdapter);

                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        if (position == currChapter) {
                            ((DrawerLayout)findViewById(R.id.drawer_layout)).closeDrawer(Gravity.LEFT);
                            return;
                        }
                        currChapter = position;
                        init_chapter();
                        scrollView.setScrollY(0);
                    }
                });
            }
        };

        // Load from previous read
        SharedPreferences sp = getSharedPreferences("readerChapter", Context.MODE_PRIVATE);
        if (sp.contains(String.valueOf(book_id))) {
            currChapter = sp.getInt(String.valueOf(book_id), 0);
        }

        init_chapter();

        scrollView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();
                switch (action) {
                    case MotionEvent.ACTION_DOWN:
                        if (velocityTracker == null)
                            velocityTracker = VelocityTracker.obtain();
                        else
                            velocityTracker.clear();
                        velocityTracker.addMovement(event);

                        destroy_timer();
                        init_timer();
                        timer.schedule(timerTask,0,1000);
                        break;
                    case MotionEvent.ACTION_MOVE:
                        velocityTracker.addMovement(event);
                        velocityTracker.computeCurrentVelocity(50);
                        current_speed = Math.abs(velocityTracker.getYVelocity());
                        long current_time = System.currentTimeMillis();
                        if (current_time >= last_record_time + 50) {
                            Log.d("speed",String.valueOf(current_speed));

                            sequence.add(current_speed);
                            last_record_time = current_time;
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        current_speed = 0;

                        timer.cancel();
                        break;
                }
                return false;
            }
        });
    }

    public void changeStatusIconCollor(boolean setDark) {
        View decorView = getWindow().getDecorView();
        if(decorView != null){
            int vis = decorView.getSystemUiVisibility();
            if(setDark){
                vis |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
            } else{
                vis &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
            }
            decorView.setSystemUiVisibility(vis);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        SharedPreferences sp = getSharedPreferences("readerChapter", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putInt(String.valueOf(book_id), currChapter);
        editor.commit();
    }

    private void init_chapter() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                ChapterObj1 chapterObj1 = RecomService.getRecomService().getChapter(book_id, currChapter);
                book_text = chapterObj1.getBody();
                chapter_title = chapterObj1.getTitle();
                total_chapter = chapterObj1.getTotal();

                book_text = "\u3000\u3000" + book_text;
                book_text = book_text.replaceAll("\n", "\n\u3000\u3000");

                handler.sendEmptyMessage(0);

            }
        }).start();
    }

    private void init_timer() {
        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Log.d("submit_sequence",String.valueOf(sequence.size()));
                        RecomService.getRecomService().submit_read_speed(book_id,sequence,MainActivity.ax,MainActivity.ay,MainActivity.az);
                        sequence.clear();
                    }
                }).start();
            }
        };
    }

    private void destroy_timer() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
    }
}
